/**
 * 在线问答
 * 控制器
 */
const OnlineQna = require("../model/onlineQna");

module.exports = {
  // 获取列表
  onlineQna_list: async (req, res) => {
    const { page, limit } = req.query;
    const offset = (page - 1) * limit;
    try {
      const informationList = await OnlineQna.findAndCountAll({
        offset,
        limit,
        order: [["create_time", "DESC"]],
      });
      res.json({ code: 1, message: "获取列表成功", data: informationList });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 添加
  onlineQna_add: async (req, res) => {
    const { question, answer } = req.body;
    try {
      // 先查询是否存在
      if (await OnlineQna.findOne({ where: { question } })) {
        return res.json({ code: -1, message: "问题已存在" });
      }
      const information = await OnlineQna.create({ question, answer });
      if (!information) {
        return res.json({ code: -1, message: "添加失败" });
      }
      res.json({ code: 1, message: "添加成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 修改
  onlineQna_update: async (req, res) => {
    const { qna_id, question, answer } = req.body;
    try {
      // 先查询是否存在
      const record = await OnlineQna.findByPk(qna_id);
      if (!record) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      if (record.question === question) {
        return res.json({ code: 1, message: "修改资料成功" });
      }
      if (await OnlineQna.findOne({ where: { question } })) {
        return res.json({ code: -1, message: "资料名称已存在" });
      }
      const row = await OnlineQna.update({ question, answer }, { where: { qna_id } });
      if (!row) {
        return res.json({ code: -1, message: "修改资料失败" });
      }
      res.json({ code: 1, message: "修改资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 删除
  onlineQna_delete: async (req, res) => {
    const { qna_id } = req.query;
    try {
      // 先查询是否存在
      const record = await OnlineQna.findByPk(qna_id);
      if (!record) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      const row = await OnlineQna.destroy({ where: { qna_id } });
      if (!row) {
        return res.json({ code: -1, message: "删除资料失败" });
      }
      res.json({ code: 1, message: "删除资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
};
